/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.weed.net.impl; 

import com.weed.core.WeedException;
import com.weed.helper.ZipUtil;
import com.weed.net.IRequest;
import com.weed.net.ISource;
import com.weed.net.listener.CallbackListener;
import com.weed.net.listener.SourceEvent;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.CookieHandler;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 *
 * @author Jason
 */
public class HttpURLRequest implements IRequest {
     public final static String HTTP_URL= "HTTP_URL";
     public final static String HTTP_COOKIES= "HTTP_COOKIES";
    
    private URL url = null;
    private ISource source= null;
    private String sessionID = null;
    private HttpURLConnection httpURLConnection =null;

    
    public HttpURLRequest(){
        //DefaultCookieHandler.getInstance();
    }

    public void init(ISource source) throws WeedException {
       this.source = source;
       HashMap map = source.getConfig();
       setUrl((URL)map.get(HTTP_URL));
    }

    public void write(Object data, CallbackListener listener) throws WeedException {
        setHttpURLConnection(createHttpUrlConn());
        if(getHttpURLConnection()!=null){
            try {
              source.processEvent(new SourceEvent(this,SourceEvent.HANDLE_BEFORE));
              String cookie = (String) source.getCache().get("Set-Cookie");
              if(cookie!=null){
                  getHttpURLConnection().setRequestProperty("Cookie", cookie);
              }
              ByteArrayOutputStream baos = (ByteArrayOutputStream)ZipUtil.gzipOutputStream(data);
              DataOutputStream dataOut = new DataOutputStream(httpURLConnection.getOutputStream());
              dataOut.write(baos.toByteArray());
              dataOut.flush();
              dataOut.close();
              try{
                 source.processEvent(new SourceEvent(this,SourceEvent.HANDLE));
              }catch(Exception ex){}
              InputStream is = httpURLConnection.getInputStream();
              Object obj = ZipUtil.gzipInputStream(is);
              is.close();
              if (cookie == null) {
                cookie = getHttpURLConnection().getHeaderField("Set-Cookie");
                source.getCache().put("Set-Cookie", cookie);
              }
              source.processEvent(new SourceEvent(this,SourceEvent.HANDLE_AFTER));
              if(listener!=null)
                 listener.callback(this, obj);
            } catch (Exception ex) {
                throw new WeedException(ex);
            }finally{
                httpURLConnection.disconnect();
                httpURLConnection = null;
            }
        }
    }

   public void close() {
            this.url = null;
            this.source= null;
            this.sessionID = null;
    }

    /**
     * @return the url
     */
    public URL getUrl() {
        return url;
    }

    /**
     * @param url the url to set
     */
    public void setUrl(URL url) {
        this.url = url;
    }
    /**
     * 创建一个连接。
     * @return
     * @throws WeedException
     */
    protected  HttpURLConnection createHttpUrlConn() throws WeedException{
        HttpURLConnection conn = null;
        try {
            URL url = getUrl();
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestProperty("Content-type", "application/octet-stream");
            conn.setRequestProperty("Accept-Language","zh-cn,zh;q=0.5");
            conn.setRequestProperty("Accept-Encoding","gzip,deflate");
            conn.setRequestProperty("Accept-Charset","GB2312,utf-8;q=0.7,*;q=0.7");
            conn.setUseCaches(false);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            return conn;
        } catch (Exception ex) {
            throw new WeedException(ex);
        }
    }


    /**
     * @return the httpURLConnection
     */
    public HttpURLConnection getHttpURLConnection() {
        return httpURLConnection;
    }

    /**
     * @param httpURLConnection the httpURLConnection to set
     */
    public void setHttpURLConnection(HttpURLConnection httpURLConnection) {
        this.httpURLConnection = httpURLConnection;
    }

    /**
     * 解析出cookies;
     * @param raw
     * @return
     */
    protected static String parseCookie(String raw) {
        String c = raw;
        if (raw != null) {
          int endIndex = raw.indexOf(";");
          if (endIndex >= 0) {
            c = raw.substring(0, endIndex);
          }
        }
        return c;
    }

}
